import 'package:flutter/material.dart';

class NamedRouteSkipDemo extends StatefulWidget {
  const NamedRouteSkipDemo({Key? key}) : super(key: key);

  @override
  _NamedRouteSkipDemoState createState() => _NamedRouteSkipDemoState();
}

class _NamedRouteSkipDemoState extends State<NamedRouteSkipDemo> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      routes: <String, WidgetBuilder>{
        '/': (context) => NamedMainPage(),
        '/test': (context) => TestNamedPageRout(""), // 需要进行拦截才能将参数正确传入
      },
    );
  }
}

class NamedMainPage extends StatefulWidget {
  const NamedMainPage({Key? key}) : super(key: key);

  @override
  _NamedMainPageState createState() => _NamedMainPageState();
}

class _NamedMainPageState extends State<NamedMainPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("NamedMainPage"),
        ),
        body: Container(
          padding: EdgeInsets.all(16),
          child: Column(
            children: [
              buildSizedBox(context, '资讯'),
              buildSizedBox(context, '设置'),
            ],
          ),
        ));
  }

  SizedBox buildSizedBox(BuildContext context, String title) {
    return SizedBox(
      width: double.infinity,
      child: RaisedButton(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        child: Text(title),
        onPressed: () {
          Navigator.of(context).pushNamed("/test", arguments: {'title': title});
        },
      ),
    );
  }
}

class TestNamedPageRout extends StatefulWidget {
  final String title;

  const TestNamedPageRout(this.title, {Key? key}) : super(key: key);

  @override
  _TestNamedPageRoutState createState() => _TestNamedPageRoutState();
}

class _TestNamedPageRoutState extends State<TestNamedPageRout> {
  String currentTitle = "";

  @override
  Widget build(BuildContext context) {
    currentTitle = widget.title;
    var arguments = ModalRoute.of(context)!.settings.arguments;
    if (arguments != null && arguments is Map) {
      Map pageParams = arguments;
      if (pageParams.containsKey('title')) {
        currentTitle = pageParams['title'];
      }
    }
    return Scaffold(
      appBar: AppBar(
        title: Text(currentTitle),
      ),
      body: Center(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.pop(context);
        },
        child: Icon(Icons.arrow_back),
      ),
    );
  }
}
